define(function (require) {
    require('bootstrapValidator');
    require('messager');
    require('table');
    require('typeahead');
    require('doctor-data');
    require('fileinput');
    require('daterangepicker');
    require('doctor-select');
    require('moment');
    require('clockpicker');
    require('datetimepicker');
    require('iCheck');
    require('typeahead');

    $.module("BASE.Budget", function () {
        let year = SYS.Tool.formatterByDaterule(new Date().getTime(), 'yyyy');
        let month = SYS.Tool.formatterByDaterule(new Date().getTime(), 'mm');

        return {
            init: function () {
                this.loadData();
                this.loadEvent();
            },
            clearDatas:function ()  {
                let that = this;

                $("#fm #_id").val(0);
                $("#fm #OrgId").val('').removeAttr('data-id');
                $("#fm #CompanyId").val('').removeAttr('data-id');
                $("#fm #CostCenterId").val('').removeAttr('data-id');

                $("#fm #PeriodYear").val(year);
                $("#fm #VerionNumber").val('');

                $("#fm input[name='Actived'][value='1']").iCheck('check');
                $('#fm').bootstrapValidator('resetForm', true);



                $('#InternalCompanyId').val('').removeAttr('data-id');
                $('#fm_budgetProduct #MaterialId').val('').removeAttr('data-id');
                $('#fm_budgetProduct #MaterialCode').val('');
                $('#fm_budgetProduct #MaterialName').val('');
                $('#fm_budgetProduct #PackQuantity').val('');
                $('#fm_budgetProduct #StdPackQuantity').val('');
                $('#fm_budgetProduct #RevenueAmount').val(0);
                $('#fm_budgetProduct #CostAmount').val(0);
                $('#fm_budgetProduct #PeriodYear1').val(year);
                $('#fm_budgetProduct #PeriodMonth1').val(month);
                $('#fm_budgetProduct').bootstrapValidator('resetForm', true);
                $('#fm_budgetGL #InternalCompanyId2').val('').removeAttr('data-id');

                $('#fm_budgetGL #AccountViewCode').val('').removeAttr('data-id');
                $('#fm_budgetGL #GroupAccountViewCode').val('').removeAttr('data-id');
                $('#fm_budgetGL #Amount').val(0);
                $('#fm_budgetGL #PeriodYear2').val(year);
                $('#fm_budgetGL #PeriodMonth2').val(month);
                $('#fm_budgetGL').bootstrapValidator('resetForm', true);

                that.showDiv('main_div');
            },
            loadData: function (pageNumber, pageSize) {
                var that = this;

                let s_CompanyCode = $("#s_CompanyCode").val();
                let s_CompanyName = $("#s_CompanyName").val();

                // let s_create_time_begin = $("#s_create_time_begin").val();
                // let s_create_time_end = $("#s_create_time_end").val();

                SYS.Core.ajax({
                    url: "base/budget/list",
                    common: {
                        page: pageNumber ? pageNumber : 1,
                        size: pageSize ? pageSize : 20
                    },
                    data: {
                        CompanyCode: s_CompanyCode,
                        CompanyName: s_CompanyName
                    },
                    success: function (data) {
                        let obj = {
                            'pageNumber': data.data.extra.current_page,
                            'pageSize': data.data.extra.page_size,
                            'totalRows': data.data.extra.all_count,
                            'data': data.data.list
                        };

                        $("#myTable").bootstrapTable('destroy');
                        $('#myTable').bootstrapTable({
                            striped: true,
                            singleSelect: false,
                            showColumns: true,
                            showToggle: true,
                            pagination: true,
                            pageNumber: obj.pageNumber,
                            pageSize: obj.pageSize,
                            totalRows: obj.totalRows,
                            pageList: [20, 50, 100, 200],
                            sidePagination: 'server',
                            clickToSelect: true,
                            idField: 'id',
                            data: obj.data,
                            columns: [
                                // {field: 'checked', checkbox: true} ,
                                {field: 'Id', title: '预算主表ID', align: 'center'},
                                {field: 'OrgId', title: '组织机构', align: 'center',
                                    formatter: function (value, row){
                                        let html = '';
                                        if (value) {
                                            let OrgName = row.OrgName;
                                            html = OrgName + "(" + value +")";
                                        }
                                        return html;
                                    }
                                },
                                {field: 'CompanyId', title: '公司信息', align: 'center',
                                    formatter: function (value,row) {
                                        let html = '';
                                        if (value) {
                                            let CompanyName = row.CompanyName || '';
                                            let CompanyCode = row.CompanyCode || '';
                                            html = CompanyCode + "-" + CompanyName + "<br/>(" + value +")";
                                        }
                                        return html;
                                    }
                                },
                                {field: 'CostCenterId', title: '成本信息', align: 'center',
                                    formatter: function (value,row) {
                                        let html = '';
                                        if (value) {
                                            let costCenterCode = row.CostCenterCode;
                                            let costCenterName = row.CostCenterName;
                                            html = costCenterCode + "-" + costCenterName + "<br/>(" + value +")";
                                        }
                                        return html;
                                    }
                                },
                                {field: 'InternalCompanyId', title: '关联公司', align: 'center',
                                    formatter: function (value, row){
                                        let html = '';
                                        if (value) {
                                            let internalCompanyCode = row.InternalCompanyCode || '';
                                            let internalCompanyName = row.InternalCompanyName || '';
                                            html = internalCompanyCode + "-" + internalCompanyName + "<br />(" + value + ")";
                                        }
                                        return html;
                                    }
                                },
                                {field: 'PeriodYear', title: '会计年', align: 'center'},
                                {field: 'VerionNumber', title: '排序号', align: 'center'},

                                {field: 'create_user_id', title: '创建人', align: 'center',
                                    formatter: function (value,row) {
                                        if (value) {
                                            return row.create_user_name + "<br/>(" + value + ")"
                                        }
                                    }
                                },
                                {field: 'create_time', title: '创建时间', align: 'center',
                                    formatter: function (value,row) {
                                        if (value) {
                                            return SYS.Tool.formatterNowTime(value)
                                        }
                                    }
                                },
                                {field: 'Actived', title: '是否启用', align: 'center',
                                    formatter: function (value,row) {
                                        return value == 1 ? '<label class="text-success">启用</label>' : '<label class="text-danger">不启用</label>';
                                    }
                                },
                                {
                                    field: 'do', title: '操作', align: 'center',
                                    formatter: function (value, row, index) {
                                        let html = '';
                                        html += '<a href="javascript:void(0)" onclick="BASE.Budget.toEdit(' + row.Id + ')" class="text-do-edit"><i class="fa fa-pencil"></i> 编辑</a> ';
                                        html += '<a href="javascript:void(0)" onclick="BASE.Budget.toRemove(' + row.Id + ')" class="text-do-remove"><i class="fa fa-trash"></i> 删除</a> ';
                                        html += '<a href="javascript:void(0)" onclick="BASE.Budget.toBudgetProduct(' + row.Id + ')" class="text-do-view"><i class="fa fa-file-text-o"></i> 明细(产品类)</a> ';
                                        html += '<a href="javascript:void(0)" onclick="BASE.Budget.toBudgetGL(' + row.Id + ')" class="text-do-view"><i class="fa fa-file-text-o"></i> 明细(总账类)</a> ';
                                        return html;
                                    }
                                }
                            ],
                            onPageChange: function(number, size){
                                that.loadData(number, size);
                            },
                            onRefreshTable: function () {
                                that.loadData();
                            },
                            onClickCell: function (field, value, row, $element) {
                            }
                        });
                    }
                });
            },
            loadBudgetProductData: function (budgetId, pageNumber, pageSize) {
                var that = this;

                $("#indexMask").show();

                let s_id = $("#s_id").val();
                let s_name = $("#s_name").val();

                // let s_create_time_begin = $("#s_create_time_begin").val();
                // let s_create_time_end = $("#s_create_time_end").val();

                SYS.Core.ajax({
                    url: "base/budgetProduct/list",
                    common: {
                        page: pageNumber ? pageNumber : 1,
                        size: pageSize ? pageSize : 20
                    },
                    data: {
                        BudgetId: budgetId
                    },
                    success: function (data) {
                        let obj = {
                            'pageNumber': data.data.extra.current_page,
                            'pageSize': data.data.extra.page_size,
                            'totalRows': data.data.extra.all_count,
                            'data': data.data.list
                        };

                        $("#indexMask").hide();

                        $("#myTable1").bootstrapTable('destroy');
                        $('#myTable1').bootstrapTable({
                            striped: true,
                            singleSelect: false,
                            showColumns: true,
                            showToggle: true,
                            pagination: true,
                            pageNumber: obj.pageNumber,
                            pageSize: obj.pageSize,
                            totalRows: obj.totalRows,
                            pageList: [20, 50, 100, 200],
                            sidePagination: 'server',
                            // clickToSelect: true,
                            idField: 'id',
                            data: obj.data,
                            columns: [
                                // {field: 'checked', checkbox: true} ,
                                {field: 'Id', title: '编号', align: 'center'},
                                {field: 'BudgetId', title: '预算主表Id', align: 'center'},
                                {field: 'InternalCompanyId', title: '关联公司', align: 'center',
                                    formatter: function (value, row){
                                        let html = '';

                                        if (value) {
                                            let InternalCompanyCode = row.InternalCompanyCode || '';
                                            let InternalCompanyName = row.InternalCompanyName || '';
                                            html = InternalCompanyCode + "<br />" + InternalCompanyName + "<br />" + "(" + value + ")";
                                        }
                                        return html;
                                    }
                                },
                                // {field: 'PeriodId', title: '会计期间信息', align: 'center',
                                //     formatter: function (value, row){
                                //         let html = '';
                                //
                                //         if (value) {
                                //             let PeriodCode = row.PeriodCode || '';
                                //             html = PeriodCode + "<br />" + "(" + value + ")";
                                //         }
                                //         return html;
                                //     }
                                // },
                                {field: 'PeriodYear', title: '会计期间-年', align: 'center'},
                                {field: 'PeriodMonth', title: '会计期间-月', align: 'center'},
                                {field: 'MaterialId', title: '产品信息', align: 'center'},
                                {field: 'MaterialCode', title: '产品编码', align: 'center'},
                                {field: 'MaterialName', title: '产品名称', align: 'center'},
                                {field: 'PackQuantity', title: '预算数量（自然箱）', align: 'center'},
                                {field: 'StdPackQuantity', title: '预算数量（标准箱）', align: 'center'},
                                {field: 'RevenueAmount', title: '预算金额', align: 'center'},
                                {field: 'CostAmount', title: '预算成本', align: 'center'},
                                {
                                    field: 'do', title: '操作', align: 'center',
                                    formatter: function (value, row, index) {
                                        return '<a href="javascript:void(0)" onclick="BASE.Budget.toRemoveBudgetProduct(' + row.Id + ',' + budgetId + ')" class="text-do-remove"><i class="fa fa-trash"></i> 删除</a>';
                                    }
                                }
                            ],
                            onPageChange: function(number, size){
                                that.loadBudgetProductData(budgetId,number, size);
                            },
                            onRefreshTable: function () {
                                that.loadBudgetProductData(budgetId);
                            },
                            onClickCell: function (field, value, row, $element) {
                            }
                        });
                    }
                });
            },
            loadBudgetGLData: function (budgetId, pageNumber, pageSize) {
                var that = this;

                let s_id = $("#s_id").val();
                let s_name = $("#s_name").val();

                // let s_create_time_begin = $("#s_create_time_begin").val();
                // let s_create_time_end = $("#s_create_time_end").val();

                SYS.Core.ajax({
                    url: "base/budgetGL/list",
                    common: {
                        page: pageNumber ? pageNumber : 1,
                        size: pageSize ? pageSize : 20
                    },
                    data: {
                        BudgetId: budgetId
                    },
                    success: function (data) {
                        let obj = {
                            'pageNumber': data.data.extra.current_page,
                            'pageSize': data.data.extra.page_size,
                            'totalRows': data.data.extra.all_count,
                            'data': data.data.list
                        };

                        $("#myTable2").bootstrapTable('destroy');
                        $('#myTable2').bootstrapTable({
                            striped: true,
                            singleSelect: false,
                            showColumns: true,
                            showToggle: true,
                            pagination: true,
                            pageNumber: obj.pageNumber,
                            pageSize: obj.pageSize,
                            totalRows: obj.totalRows,
                            pageList: [20, 50, 100, 200],
                            sidePagination: 'server',
                            // clickToSelect: true,
                            idField: 'id',
                            data: obj.data,
                            columns: [
                                // {field: 'checked', checkbox: true},
                                {field: 'Id', title: '编号', align: 'center'},
                                {field: 'BudgetId', title: '预算主表Id', align: 'center',                                },
                                {field: 'InternalCompanyId', title: '关联公司', align: 'center',
                                    formatter: function (value, row){
                                        let html = '';
                                        if (value) {
                                            let internalCompanyCode = row.InternalCompanyCode || '';
                                            let internalCompanyName = row.InternalCompanyName || '';
                                            html = internalCompanyCode + "-" + internalCompanyName + "<br />(" + value + ")";
                                        }
                                        return html;
                                    }
                                },
                                {field: 'AccountViewCode', title: '科目代码', align: 'center'},
                                {field: 'AccountViewName', title: '科目名称', align: 'center'},
                                {field: 'GroupAccountViewCode', title: '科目代码(集团)', align: 'center'},
                                {field: 'GroupAccountViewName', title: '科目名称(集团)', align: 'center'},
                                {field: 'Amount', title: '预算金额', align: 'center'},
                                {field: 'PeriodYear', title: '会计期间-年', align: 'center'},
                                {field: 'PeriodMonth', title: '会计期间-月', align: 'center'},
                                {
                                    field: 'do', title: '操作', align: 'center',
                                    formatter: function (value, row, index) {
                                        return '<a href="javascript:void(0)" onclick="BASE.Budget.toRemoveBudgetGL(' + row.Id + ',' + budgetId + ')" class="text-do-remove"><i class="fa fa-trash"></i> 删除</a>';
                                    }
                                }
                            ],
                            onPageChange: function(number, size){
                                that.loadBudgetGLData(budgetId,number, size);
                            },
                            onRefreshTable: function () {
                                that.loadBudgetGLData(budgetId);
                            },
                            onClickCell: function (field, value, row, $element) {
                            }
                        });
                    }
                });
            },
            loadEvent: function () {
                var that = this;

                // 定义编辑框form
                var $form = $("#fm");

                // 查询
                $("#search-toolbar").on('click', "#btn_search", function () {
                    that.loadData();
                }).on("keydown ", "input", function (e) {
                    if (e.keyCode == 13) {
                        that.loadData();
                    }
                });

                // 初始化搜索日期控件
                //SYS.Tool.initDaterangSearchWithHHmm('s_hx_time', 's_hx_time_begin', 's_hx_time_end');
                //SYS.Tool.initDaterangSearchWithHHmm('s_create_time', 's_create_time_begin', 's_create_time_end');


                var typeAheadArr = [
                    {id: "s_ishx", data: DOCTOR.Data.common.isuse_status}
                ];
                for (let i in typeAheadArr) {
                    let typeHead = typeAheadArr[i];
                    SYS.Tool.selectTypeahead(typeHead.id, typeHead.data);
                }

                // 组织架构
                $("#OrgId").on('click', function () {
                    DOCTOR.Select.showOrg(this);
                });
                // 报表项目父级
                $("#CompanyId").on('click', function () {
                    DOCTOR.Select.showCompany(this);
                });
                // 预算组织
                $("#CostCenterId").on('click', function () {
                    DOCTOR.Select.showCostCenter(this);
                });


                // 批量删除
                $("#btn_deletes").on('click',function(){
                    that.toRemoves();
                });

                // 绑定日期控件
                // $("#creaetdate, #hxdate").datetimepicker({
                //     minView: "hour",
                //     format: 'yyyy-mm-dd hh:ii',
                //     todayBtn: true,
                //     language: 'zh-CN', // 汉化
                //     autoclose: true    // 选择日期后自动关闭
                // }).on('changeDate', function (ev) {
                //     var field = $(this).attr("id");
                //     $form.find("input[data-field='" + field + "']").val(ev.date.getTime());
                // });

                // 新增
                $("#btn_add").on('click', function () {
                    that.clearDatas();

                    $("#btn-add-div").show();
                    $("#btn-edit-div").hide();
                    that.showDiv('edit_div');
                });


                // 关联公司
                $("#InternalCompanyId, #InternalCompanyId2, #InternalCompanyId3").on('click', function () {
                    DOCTOR.Select.showCompany(this);
                });
                // 产品
                $("#MaterialId").on('click', function () {
                    DOCTOR.Select.showMaterial(this);
                });
                // 会计期间
                $("#PeriodId").on('click', function () {
                    DOCTOR.Select.showPeriod(this);
                });
                // 科目
                $("#AccountViewCode, #GroupAccountViewCode").on('click', function () {
                    DOCTOR.Select.showAccountView(this);
                });
                // 新增
                $("#btn_add_budgetProduct").on('click', function () {
                    that.clearDatas();

                    $('#myModal1').modal('show');
                    that.showDiv('budgetProduct_div');
                });

                // 新增
                $("#btn_add_budgetGL").on('click', function () {
                    that.clearDatas();

                    $('#myModal2').modal('show');
                    that.showDiv('budgetGL_div');
                });

                $(".i-checks").iCheck({checkboxClass:"icheckbox_square-orange", radioClass:"iradio_square-orange"});
                $("#btn_import_product").on('click', function () {

                    $('#fm_product_import').bootstrapValidator('disableSubmitButtons', false);

                    $("#import_product_tip").html('');
                    $("#import_product_file").empty();
                    $("#import_product_file").fileinput('refresh', {
                        uploadUrl: '/base/budgetProduct/importData?',
                        showUploadedThumbs: false,
                        browseClass: 'btn btn-main',
                        allowedFileExtensions: ["xls", "xlsx"],
                        uploadExtraData: function(previewId, index) {   //额外参数的关键点
                            var obj = {};
                            obj.parameters = JSON.stringify({
                                common:{},
                                data: {
                                    BudgetId: $("#product_import_id").val()
                                }
                            });
                            return obj;
                        }
                    }).on('fileuploaded', function (event, data) {
                        let obj = data.response;

                        $("#import_product_tip").html(obj.msg);
                    });

                    that.showDiv('import_product_div');
                });
                $("#btn_import_gl").on('click', function () {

                    $('#fm_gl_import').bootstrapValidator('disableSubmitButtons', false);

                    $("#import_gl_tip").html('');
                    $("#import_gl_file").empty();
                    $("#import_gl_file").val('');
                    $("#import_gl_file").fileinput('refresh', {
                        uploadUrl: '/base/budgetGL/importData?',
                        showUploadedThumbs: false,
                        browseClass: 'btn btn-main',
                        allowedFileExtensions: ["xls", "xlsx"],
                        uploadExtraData: function(previewId, index) {   //额外参数的关键点
                            var obj = {};
                            obj.parameters = JSON.stringify({
                                common:{},
                                data: {
                                    BudgetId: $("#gl_import_id").val()
                                }
                            });
                            return obj;
                        }
                    }).on('fileuploaded', function (event, data) {
                        var data = data.response;

                        $("#import_gl_tip").html(data.msg);
                    });

                    that.showDiv('import_gl_div');
                });


                // 返回
                $(".back_list").on('click', function () {
                    that.clearDatas();

                    that.showDiv('main_div');
                });

                $(".back_list_2").on('click', function () {
                    that.clearDatas();

                    let budgetId = $("#product_import_id").val();
                    that.loadBudgetProductData(budgetId)
                    that.showDiv('budgetProduct_div');
                });
                $(".back_list_3").on('click', function () {
                    that.clearDatas();

                    let budgetId = $("#gl_import_id").val();
                    that.loadBudgetGLData(budgetId);
                    that.showDiv('budgetGL_div');
                });

                //
                $('#fm').bootstrapValidator({
                    excluded: ':disabled',
                    feedbackIcons: {
                        valid: 'glyphicon glyphicon-ok',
                        invalid: 'glyphicon glyphicon-remove',
                        validating: 'glyphicon glyphicon-refresh'
                    },
                    fields: {
                        Name: {
                            validators: {
                                notEmpty: {
                                    message: '此项必填'
                                }
                            }
                        },
                        SortNumber: {
                            validators: {
                                // notEmpty: {
                                //     message: '此项必填'
                                // },
                                regexp: {
                                    regexp: /^[1-9]\d*$/i,
                                    message: '格式不正确，必须大于0'
                                }
                            }
                        }
                    }
                }).on('success.form.bv', function (e) {
                    e.preventDefault();

                    let OrgId = $("#OrgId").attr('data-id') || 0;
                    let CompanyId = $("#CompanyId").attr('data-id') || "";
                    let CostCenterId = $("#CostCenterId").attr('data-id') || "";
                    let PeriodYear = $("#PeriodYear").val();
                    if(OrgId === 0) {
                        $.messager.popup("请选择一个管理口径组织架构，在提交", 'error');
                        $('#fm').bootstrapValidator('disableSubmitButtons', false);
                        return;
                    }
                    if(CompanyId === "") {
                        $.messager.popup("请选择一个法人公司，在提交", 'error');
                        $('#fm').bootstrapValidator('disableSubmitButtons', false);
                        return;
                    }
                    if(CostCenterId === "") {
                        $.messager.popup("请选择一个预算组织，在提交", 'error');
                        $('#fm').bootstrapValidator('disableSubmitButtons', false);
                        return;
                    }

                    if(PeriodYear === "" || PeriodYear.length == 0) {
                        $.messager.popup("会计期间-年必填，请输入后在提交", 'error');
                        $('#fm').bootstrapValidator('disableSubmitButtons', false);
                        return;
                    } else {
                        if(!/^\d+$/.test(PeriodYear)) {
                            $.messager.popup("会计期间-年,填写为数字，在提交", 'error');
                            $('#fm').bootstrapValidator('disableSubmitButtons', false);
                            return;
                        }
                    }

                    that.save();
                });

                $('#fm_budgetProduct').bootstrapValidator({
                    excluded: ':disabled',
                    feedbackIcons: {
                        valid: 'glyphicon glyphicon-ok',
                        invalid: 'glyphicon glyphicon-remove',
                        validating: 'glyphicon glyphicon-refresh'
                    },
                    fields: {
                        RevenueAmount: {
                            validatorg: {
                                notEmpty: {
                                    message: '此项必填'
                                },
                                regexp: {
                                    regexp: /^[1-9][0-9]*$/,
                                    message: '请输入正整数'
                                }
                            }
                        },
                        CostAmount: {
                            validatorg: {
                                notEmpty: {
                                    message: '此项必填'
                                },
                                regexp: {
                                    regexp: /^[1-9][0-9]*$/,
                                    message: '请输入正整数'
                                }
                            }
                        },
                        // PeriodYear1: {
                        //     validators: {
                        //         notEmpty: {
                        //             message: '此项必填'
                        //         },
                        //         regexp: {
                        //             regexp: /^[1-9][0-9]*$/,
                        //             message: '请输入正整数'
                        //         }
                        //     }
                        // },
                        PeriodMonth1: {
                            validators: {
                                notEmpty: {
                                    message: '此项必填'
                                },
                                regexp: {
                                    regexp: /^[1-9][0-9]*$/,
                                    message: '请输入正整数'
                                }
                            }
                        },
                    }
                }).on('success.form.bv', function (e) {
                    e.preventDefault();

                    //let InternalCompanyId = $("#InternalCompanyId").attr('data-id') || "";
                    let MaterialId = $("#MaterialId").attr('data-id') || "";

                    // if(InternalCompanyId === "") {
                    //     $.messager.popup("请选择一个关联公司，在提交", 'error');
                    //     $('#fm_budgetProduct').bootstrapValidator('disableSubmitButtons', false);
                    //     return;
                    // }
                    if(MaterialId === "") {
                        $.messager.popup("请选择一个产品，在提交", 'error');
                        $('#fm_budgetProduct').bootstrapValidator('disableSubmitButtons', false);
                        return;
                    }

                    that.saveBudgetProduct();
                });

                $('#fm_budgetGL').bootstrapValidator({
                    excluded: ':disabled',
                    feedbackIcons: {
                        valid: 'glyphicon glyphicon-ok',
                        invalid: 'glyphicon glyphicon-remove',
                        validating: 'glyphicon glyphicon-refresh'
                    },
                    fields: {
                        // PeriodYear2: {
                        //     validators: {
                        //         notEmpty: {
                        //             message: '此项必填'
                        //         },
                        //         regexp: {
                        //             regexp: /^[1-9][0-9]*$/,
                        //             message: '请输入正整数'
                        //         }
                        //     }
                        // },
                        PeriodMonth2: {
                            validators: {
                                notEmpty: {
                                    message: '此项必填'
                                },
                                regexp: {
                                    regexp: /^[1-9][0-9]*$/,
                                    message: '请输入正整数'
                                }
                            }
                        },
                    }
                }).on('success.form.bv', function (e) {
                    e.preventDefault();
                    let InternalCompanyId = $("#InternalCompanyId2").attr('data-id') || "";
                    let AccountViewCode = $("#AccountViewCode").attr('data-id') || "";

                    // if(InternalCompanyId === "") {
                    //     $.messager.popup("请选择一个关联公司，在提交", 'error');
                    //     $('#fm_budgetGL').bootstrapValidator('disableSubmitButtons', false);
                    //     return;
                    // }
                    if(AccountViewCode === "") {
                        $.messager.popup("请选择一个关联科目，在提交", 'error');
                        $('#fm_budgetGL').bootstrapValidator('disableSubmitButtons', false);
                        return;
                    }

                    that.saveBudgetGL();
                });

            },
            toEdit: function (id) {
                var that = this;
                that.clearDatas();

                $("#btn-add-div").hide();
                $("#btn-edit-div").show();

                SYS.Core.ajax({
                    url: 'base/budget/detail',
                    common: {},
                    data: {
                        Id: id || 0
                    },
                    success: function (data) {
                        if (data.code == 1) {
                            var obj = data.data;

                            const id = obj.Id;
                            const OrgId = obj.OrgId;
                            const OrgName = obj.OrgName;
                            const CompanyId = obj.CompanyId;
                            const CompanyCode = obj.CompanyCode;

                            const CompanyName = obj.CompanyName;
                            const CostCenterId = obj.CostCenterId;

                            const CostCenterName = obj.CostCenterName;

                            const InternalCompanyId = obj.InternalCompanyId;
                            const InternalCompanyName = obj.InternalCompanyName;
                            const InternalCompanyCode = obj.InternalCompanyCode;

                            const PeriodYear = obj.PeriodYear;
                            const VerionNumber = obj.VerionNumber;
                            const Actived = obj.Actived;

                            $("#_id").val(id);
                            $("#OrgId").attr('data-id', OrgId).val(OrgName != null ? OrgName : '');
                            $("#CompanyId").attr('data-id', CompanyId).attr('data-code', CompanyCode).attr('data-name', CompanyName).val(CompanyName);
                            $("#CostCenterId").attr('data-id', CostCenterId).val(CostCenterName != null ? CostCenterName : '');
                            $("#InternalCompanyId3").attr('data-id', InternalCompanyId).val(InternalCompanyName != null ? InternalCompanyName : '');

                            $("#PeriodYear").val(PeriodYear);
                            $("#VerionNumber").val(VerionNumber);
                            $("input[name='Actived'][value='" + Actived + "']").iCheck('check');

                            that.showDiv('edit_div');
                        }
                    }
                });
            },
            toBudgetProduct: function (id) {
                var that = this;

                // 设置budgetId
                $("#fm_budgetProduct #BudgetId").val(id);
                $("#product_import_id").val(id);
                $("#myTable1").bootstrapTable('destroy');

                this.loadBudgetProductData(id);
                that.showDiv('budgetProduct_div');

                // SYS.Core.ajax({
                //     url: 'base/budget/detail',
                //     common: {},
                //     data: {
                //         Id: id || 0
                //     },
                //     success: function (data) {
                //         if (data.code == 1) {
                //             var obj = data.data;
                //
                //             that.showDiv('edit_div');
                //         }
                //     }
                // });
            },
            toBudgetGL: function (id) {
                var that = this;

                // 设置budgetId
                $("#BudgetId2").val(id);
                $("#gl_import_id").val(id);
                $("#myTable2").bootstrapTable('destroy');

                this.loadBudgetGLData(id);
                that.showDiv('budgetGL_div');
            },
            save: function () {
                var that = this;

                let id = $("#_id").val();
                let OrgId = $("#OrgId").attr('data-id');
                let CompanyId = $("#CompanyId").attr('data-id') || "";

                let CompanyCode = $("#CompanyId").attr('data-code') || "";
                let CompanyName = $("#CompanyId").attr('data-name') || "";

                let CostCenterId = $("#CostCenterId").attr('data-id')  || "";

                let InternalCompanyId3 = $("#InternalCompanyId3").attr('data-id') || "";

                let PeriodYear = $("#PeriodYear").val();
                let VerionNumber = $("#VerionNumber").val();
                let Actived = $("input[name='Actived']:checked").val()

                SYS.Core.ajax({
                    url: 'base/budget/save',
                    common: {},
                    data:{
                        Id: id || 0,
                        OrgId: OrgId || 0,
                        CompanyId: CompanyId,
                        CompanyCode: CompanyCode,
                        CompanyName: CompanyName,
                        CostCenterId: CostCenterId,
                        InternalCompanyId: InternalCompanyId3,
                        PeriodYear: PeriodYear || 0,
                        VerionNumber: VerionNumber,
                        Actived: Actived
                    },
                    success: function (data) {
                        if(data.code == 1) {
                            $.messager.popup(data.msg, 'success');

                            that.loadData();
                            that.showDiv('main_div');
                        } else {
                            $('#fm').bootstrapValidator('disableSubmitButtons', false);
                            $.messager.popup(data.msg, 'error');
                        }
                    }
                })
            },
            saveBudgetProduct: function () {
                var that = this;

                let BudgetId = $("#BudgetId").val();
                //let InternalCompanyId = $("#InternalCompanyId").attr('data-id');
                // let PeriodId = $("#PeriodId").attr('data-id');
                let PeriodYear = $("#PeriodYear1").val();
                let PeriodMonth = $("#PeriodMonth1").val();
                let MaterialId = $("#MaterialId").attr('data-id');
                let MaterialCode = $("#MaterialCode").val();
                let MaterialName = $("#MaterialName").val();
                let PackQuantity = $("#PackQuantity").val();
                let StdPackQuantity = $("#StdPackQuantity").val();
                let RevenueAmount = $("#RevenueAmount").val();
                let CostAmount = $("#CostAmount").val();

                SYS.Core.ajax({
                    url: 'base/budgetProduct/save',
                    common: {},
                    data:{
                        Id: 0,
                        BudgetId: BudgetId,
                        //InternalCompanyId: InternalCompanyId,
                        PeriodYear: PeriodYear,
                        PeriodMonth: PeriodMonth,
                        MaterialId: MaterialId,
                        MaterialCode: MaterialCode,
                        MaterialName: MaterialName,
                        PackQuantity: PackQuantity,
                        StdPackQuantity: StdPackQuantity,
                        RevenueAmount: RevenueAmount || 0,
                        CostAmount: CostAmount || 0,
                    },
                    success: function (data) {
                        if(data.code == 1) {
                            $.messager.popup(data.msg, 'success');

                            that.loadBudgetProductData(BudgetId);
                            $('#myModal1').modal('hide');
                        } else {
                            $('#fm_budgetProduct').bootstrapValidator('disableSubmitButtons', false);
                            $.messager.popup(data.msg, 'error');
                        }
                    }
                })
            },
            saveBudgetGL: function () {
                var that = this;

                let BudgetId = $("#BudgetId2").val();
                //let InternalCompanyId = $("#InternalCompanyId2").attr('data-id');
                let AccountViewCode = $("#AccountViewCode").attr('data-id');
                let AccountViewName = $("#AccountViewCode").val();
                let GroupAccountViewCode = $("#GroupAccountViewCode").attr('data-id');
                let Amount = $("#Amount").val();
                let PeriodYear = $("#PeriodYear2").val();
                let PeriodMonth = $("#PeriodMonth2").val();

                SYS.Core.ajax({
                    url: 'base/budgetGL/save',
                    common: {},
                    data:{
                        Id: 0,
                        BudgetId: BudgetId,
                        //InternalCompanyId: InternalCompanyId,
                        AccountViewCode: AccountViewCode,
                        AccountViewName: AccountViewName,
                        // GroupAccountViewCode: GroupAccountViewCode,
                        Amount:Amount,
                        PeriodYear:PeriodYear,
                        PeriodMonth:PeriodMonth,

                    },
                    success: function (data) {
                        if(data.code == 1) {
                            $.messager.popup(data.msg, 'success');

                            that.loadBudgetGLData(BudgetId);
                            $('#myModal2').modal('hide');
                        } else {
                            $('#fm_budgetGL').bootstrapValidator('disableSubmitButtons', false);
                            $.messager.popup(data.msg, 'error');
                        }
                    }
                })
            },
            toRemove: function (id) {
                var that = this;

                $.messager.confirm("产品类、总账类相关联数据，也会一并删除，确定要删除吗？", function() {
                    SYS.Core.ajax({
                        url: "base/budget/delete",
                        common: {},
                        data: {
                            Id: id
                        },
                        success: function (data) {
                            if(data.code == 1){
                                $.messager.popup(data.msg, "success");
                                that.loadData();
                            }else{
                                $.messager.popup(data.msg,'error');
                            }
                        }
                    })
                });
            },
            toRemoves: function () {
                var that = this;
                var selRows = $('#myTable').bootstrapTable('getSelections');
                var delIds = [];
                if(selRows.length > 0){
                    $.each(selRows, function (i, obj) {
                        if(obj.id > 0){
                            delIds.push(obj.id);
                        }
                    });
                    $.messager.confirm("确定批量删除吗？", function() {
                        SYS.Core.ajax({
                            url: "base/budget/delete",
                            common: {},
                            data: {
                                ids: delIds
                            },
                            success: function (data) {
                                if(data.code == 1){
                                    $.messager.popup(data.msg,"success");
                                    that.loadData();
                                }else{
                                    $.messager.popup(data.msg,'error');
                                }
                            }
                        })
                    });
                }else{
                    $.messager.popup('请选择一条记录后再删除','warn');
                }
            },
            toRemoveBudgetProduct: function (id, BudgetId) {
                var that = this;
                $.messager.confirm("确定要删除吗？", function() {
                    SYS.Core.ajax({
                        url: "base/budgetProduct/delete",
                        common: {},
                        data: {
                            ids: [id]
                        },
                        success: function (data) {
                            if(data.code == 1){
                                $.messager.popup(data.msg, "success");
                                that.loadBudgetProductData(BudgetId);
                            }else{
                                $.messager.popup(data.msg,'error');
                            }
                        }
                    })
                });
            },
            toRemoveBudgetGL: function (id, BudgetId) {
                var that = this;
                $.messager.confirm("确定要删除吗？", function() {
                    SYS.Core.ajax({
                        url: "base/budgetGL/delete",
                        common: {},
                        data: {
                            ids: [id]
                        },
                        success: function (data) {
                            if(data.code == 1){
                                $.messager.popup(data.msg, "success");
                                that.loadBudgetGLData(BudgetId);
                            }else{
                                $.messager.popup(data.msg,'error');
                            }
                        }
                    })
                });
            },
            showDiv: function (div) {
                var divs = ['main_div', 'edit_div','import_product_div','import_gl_div', 'budgetProduct_div', 'budgetGL_div'];
                for(var i=0; i<divs.length; i++){
                    $("#" + divs[i]).hide();
                }
                $("#" + div).show();
            }
        }
    });


    BASE.Budget.init();
});